﻿using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace AmuTools.IO
{
    public class FileHelper
    {
        public static T ReadJsonFile<T>(string jsonFileName)
        {
            string json = GetTextFileContent(jsonFileName);
            return JsonConvert.DeserializeObject<T>(json);
        }

        public static void SaveToJsonFile(string jsonFileName, object obj)
        {
            string json = JsonConvert.SerializeObject(obj);
            CreateTextFile(jsonFileName, json);
        }

        public static string GetTextFileContent(string fileName)
        {
            StreamReader sr = new StreamReader(fileName, Encoding.Default);
            string content, result = "";
            while ((content = sr.ReadLine()) != null)
            {
                result += content.ToString() + "\r\n";
            }
            sr.Close();
            return result;
        }

        public static bool CreateTextFile(string fileName, string content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            //开始写入
            sw.Write(content);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
            return true;
        }

        public static void DelectDirectoryForce(string directory)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(directory);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }





        #region 文件占用相关函数, 暂时没完成
        /// <summary>
        /// 解除文件占用
        /// </summary>
        /// <param name="fileName"></param>
        public static void RelieveFileOccupy(string fileName)
        {
            FileInfo fileInfo = new FileInfo(fileName);
            Process[] pcs = Process.GetProcesses();
            foreach (Process p in pcs)
            {
                //确认文件
                if (p.MainWindowTitle.Contains(fileInfo.Name))
                {
                    p.Kill();//结束进程
                }
            }
        }

        [DllImport("kernel32.dll")]
        private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);
        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        /// <summary>
        /// 判断文件是否被占用
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool IsFileOccupied(string fileName)
        {
            bool result = false;
            System.IO.FileStream fileStream = null;
            try
            {
                if (!File.Exists(fileName))
                {
                    result = false;
                }
                FileStream fs = new FileStream(fileName, FileMode.Create);
                result = false;

                //IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
                //if (vHandle == HFILE_ERROR)
                //{
                //    result = true;
                //}
                //CloseHandle(vHandle);
                //File.Create(fileName);
                //fileStream = System.IO.File.Open(fileName, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None);
                result = false;
            }
            catch (System.IO.IOException ioEx)
            {
                result = true;
            }
            catch (System.Exception ex)
            {
                result = true;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
            return result;
        }
        #endregion
    }
}
